package com.cyy.view

import cn.hutool.core.io.FileUtil
import com.cyy.model.Constants
import com.cyy.model.GmodelModel
import com.cyy.srv.GenSrv
import com.jfinal.kit.Kv
import com.jfinal.plugin.activerecord.Db
import javafx.geometry.Orientation
import javafx.scene.control.RadioButton
import javafx.scene.control.SelectionMode
import javafx.stage.FileChooser
import tornadofx.*
import java.io.File

class DBView(val gmodel: GmodelModel, val genSrv: GenSrv) : View() {
    val ef = arrayOf(FileChooser.ExtensionFilter("choose db file", "*.db"))
    val isDBFile = booleanProperty()

    lateinit var rmp: RadioButton    // mysql port radiobutton
    // lateinit var rpp:RadioButton    // postgresql port radiobutton
    lateinit var rsp: RadioButton    // mssqlserver port radiobutton
    lateinit var rop: RadioButton    // oracle port radiobutton

    override val root = scrollpane(true, true) {
        form {
            prefWidth = 900.0
            hbox(5) {
                fieldset("请设置数据库参数", labelPosition = Orientation.VERTICAL) {
                    hbox {
                        // dbtyp
                        field {
                            prefWidth = 150.0
                            vbox(10) {
                                togglegroup {
                                    gmodel.dbtype.bind(selectedValueProperty())
                                    selectedToggleProperty().addListener { _, _, _ ->
                                    // 当切换数据库时，关闭之前的ActiveRecordPlug
                                        try{
                                            gmodel.dbs.clear()
                                            gmodel.tables.clear()
                                            if ((gmodel.arp.value != null)) {
//                                                Constants.closeDb(gmodel.dataSource.value)
                                                gmodel.arp.value.stop()
                                            }
                                        }catch(e:Exception){
                                            println("arp stop failed: ${e}")
                                        }
                                    }

                                    radiobutton("mysql", value = "mysql") {
                                        whenSelected {
                                            isDBFile.value = false
                                            gmodel.driver.value = "com.mysql.cj.jdbc.Driver"
                                            gmodel.user.value = "root"
                                            gmodel.pwd.value = "root"
                                            gmodel.dbname.value=""
                                            rmp.isSelected = true
                                        }
                                    }
                                    radiobutton("postgresql", value = "postgresql") {
                                        whenSelected {
                                            isDBFile.value = false
//                                        gmodel.port.value = "5432"
                                            gmodel.driver.value = "org.postgresql.Driver"
                                            gmodel.user.value = "postgres"
                                            gmodel.pwd.value = ""
                                            gmodel.dbname.value=""
                                            (form.lookup("#postgresPort") as RadioButton).isSelected = true
                                        }
                                    }
                                    radiobutton("oracle", value = "oracle") {
                                        whenSelected {
                                            isDBFile.value = false
                                            rop.isSelected = true
                                            gmodel.dbname.value=""
                                            gmodel.driver.value = "oracle.jdbc.driver.OracleDriver"

//                                        gmodel.port.value = "1521"
                                        }
                                    }
                                    radiobutton("sqlserver", value = "sqlserver") {
                                        isDBFile.value = false
                                        whenSelected {
                                            isDBFile.value = false
                                            rsp.isSelected = true
                                            gmodel.dbname.value=""
                                            gmodel.driver.value = "com.microsoft.sqlserver.jdbc.SQLServerDriver"
//                                        gmodel.port.value = "1433"
                                        }
                                    }

                                    radiobutton("sqlite", value = "sqlite") {
                                        isSelected = true
//                                        gmodel.driver.value = "org.sqlite.JDBC"
                                        whenSelected {
                                            isDBFile.value = true
                                            gmodel.driver.value = "org.sqlite.JDBC"

                                        }
                                    }
                                    radiobutton("h2", value = "h2") {
                                        whenSelected {
                                            isDBFile.value = true
                                            gmodel.driver.value = "org.h2.Driver"
                                        }
                                    }

                                }
                            }

                        }
                        field {
                            vbox(10) {
                                togglegroup {
                                    // gmodel.port.bind(selectedValueProperty())
                                    rmp = radiobutton("3306", value = "3306") { id = "mysql" }
                                    radiobutton("5432", value = "5432") { id = "postgresPort" }
                                    rop = radiobutton("1521", value = "1521")
                                    rsp = radiobutton("1433", value = "1433")
                                    selectedToggleProperty().addListener { _, _, newValue -> gmodel.port.value = newValue.properties["tornadofx.toggleGroupValue"].toString() }
                                }
                                field("PORT") {
                                    textfield(gmodel.port) {
                                        text = "3306"
                                        required(message = "Enter port for your database")
                                    }
                                }
                            }

                        }

                    }
                    separator(Orientation.HORIZONTAL)
                    hbox {
                        field("username") {
                            textfield(gmodel.user) {
                                text = "root"
                                required(message = "Enter user name for your database")
                            }
                        }
                        field("password") {
                            textfield(gmodel.pwd) {
                                text = "root"
                                required(message = "Enter user name for your database")
                            }
                        }

                    }
                    field("HOST") {
                        textfield(gmodel.host) {
                            text = "localhost"
                            required(message = "Enter host for your database")
                        }
                    }
                    separator(Orientation.HORIZONTAL)
                    field("dbname") {
                        button("choose db file") {
                            enableWhen(isDBFile)
                            action {
                                gmodel.dbs.clear()
                                gmodel.tables.clear()
                                val fn = chooseFile("choose db file", ef, FileChooserMode.Single){
                                    // p初始目录为当前项目目录
                                    initialDirectory= File(File("").canonicalPath)
                                }
                                if (fn.isNotEmpty()) {
                                    gmodel.dbname.value = "${fn.first()}"
                                    gmodel.jdbcUrl.value = "jdbc:${gmodel.dbtype.value}://${gmodel.dbname.value}"
                                }
                            }
                        }
                        textfield(gmodel.dbname) {
                            text = "/soft/pboot.db"
//                                required(message = "Enter user name for your database")
                            setOnKeyReleased {
                                gmodel.jdbcUrl.value = "jdbc:${gmodel.dbtype.value}://${gmodel.dbname.value}"
                            }
                        }
                    }
                    field("jdbcUrl") {
                        textfield(gmodel.jdbcUrl) {
                            text = "jdbc:sqlite://soft/pboot.db"
                            required(message = "Enter user name for your database")
                        }
                    }
                    field("需要移除的表名前缀，用,分隔") {
                        textfield(gmodel.removedTableNamePrefixes) {
                            text = "t_, sys_,"
                        }
                    }
                }
                separator(Orientation.VERTICAL)
                //  数据库列表
                fieldset(labelPosition = Orientation.VERTICAL) {
                    //                    label(gmodel.tableCounts)
                    field("选择数据库") {
                        listview(gmodel.dbs) {
                            id="dbList"
                            visibleWhen(gmodel.dbOK)
                            selectionModel.selectionMode = SelectionMode.SINGLE
                            bindSelected(gmodel.dbname)
                            selectionModel.selectedItemProperty().addListener { _, _, _ ->
                                (if (!selectionModel.selectedItem.isNullOrEmpty()) {
                                   try{
                                       genSrv.prapare()
                                   }catch(e:Exception){
                                       println("db change failed : ${e}")
                                   }
                                })
                            }
                        }
                    }
                }
                separator(Orientation.VERTICAL)
                // 数据库中的表
                fieldset(labelPosition = Orientation.VERTICAL) {
                    label(gmodel.tableCounts)
                    field("选择的数据库中的表有") {
                        listview(gmodel.tables) {
                            enableWhen(gmodel.dbOK)
                            selectionModel.selectionMode = SelectionMode.SINGLE
//                            bindSelected(gmodel.dbname)
                            bindSelected(gmodel.leftTable)
                            selectionModel.selectedItemProperty().addListener { _, _, _ ->
                                (if (selectionModel.selectedItem.isNullOrEmpty()) {
                                    genSrv.prapare()
//                                    println(genSrv.getAllTables())
                                })
                            }
                        }
                    }
                }
                fieldset() {
                    minWidth = 40.0
                    paddingTop = 100

                    button("->") {
                        prefHeight = 50.0
                        action {
                            //                            println(gmodel.leftTable.value)
                            if (gmodel.excludedTable.contains(gmodel.leftTable.value) || gmodel.leftTable.value.isNullOrEmpty()) {
                                return@action
                            } else {
                                gmodel.excludedTable.add(gmodel.leftTable.value)
                                gmodel.tables.remove(gmodel.leftTable.value)

                            }
                        }
                    }
                    button("<-") {
                        prefHeight = 50.0
                        action {
                            //                            println(gmodel.rightTable.value)
                            if (gmodel.tables.contains(gmodel.rightTable.value) || gmodel.rightTable.value.isNullOrEmpty()) {
                                return@action
                            } else {
                                gmodel.tables.add(gmodel.rightTable.value)
                                gmodel.excludedTable.remove(gmodel.rightTable.value)
                            }
                        }
                    }
                }
                fieldset(labelPosition = Orientation.VERTICAL) {
                    field("从左侧列表选择排除的表") {
                        listview(gmodel.excludedTable) {
                            id = "extble"
                            bindSelected(gmodel.rightTable)

                            selectionModel.selectedItemProperty().addListener { _, _, _ ->
                                (if (selectionModel.selectedItem.isNullOrEmpty()) {
//                                    println(genSrv.getAllTables())
                                })
                            }
                        }
                    }

                }
            }

        }
    }

    init {
        isDBFile.value = true

    }
}
